package cn.huiyunche.base.service.interfaces.impl;


import cn.huiyunche.base.service.constant.App;
import cn.huiyunche.base.service.constant.BVehicleConstant;
import cn.huiyunche.base.service.enums.BStowageModelEnum;
import cn.huiyunche.base.service.enums.OrderImporteStatusEnum;
import cn.huiyunche.base.service.form.OrderByExcelVo;
import cn.huiyunche.base.service.form.SOrderImportedSearchForm;
import cn.huiyunche.base.service.form.VehiClesInfoFrom;
import cn.huiyunche.base.service.interfaces.*;
import cn.huiyunche.base.service.mappers.SOrderImportedMapper;
import cn.huiyunche.base.service.mappers.ext.SOrderImportedExtMapper;
import cn.huiyunche.base.service.model.*;
import cn.huiyunche.base.service.utils.UniquenessFlagUnits;
import cn.huiyunche.base.service.vo.*;
import cn.huiyunche.tools.basic.exceptions.BusinessException;
import com.alibaba.fastjson.JSON;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by LYN on 9/19/16.
 */
@Service
public class SOrderImportedServiceImpl implements SOrderImportedService {

    private static final Logger logger = LoggerFactory.getLogger(SOrderImportedServiceImpl.class);

    @Autowired
    private SOrderService orderService;

    @Autowired
    private BAreaService areaService;

    @Autowired
    private UserService userService;

    @Autowired
    private BVehicleService vehiclesService;

    @Autowired
    private FeesService feesService;

    @Autowired
    private SOrderImportedMapper sOrderImportedMapper;

    @Autowired
    private SOrderImportedExtMapper sOrderImportedExtMapper;

    @Autowired
    private GDMapService mapService;

    @Autowired
    private BVehicleClassService bVehicleClassService;

    @Autowired
    private BStowageVehicleService bStowageVehicleService;

    @Autowired
    private SOrderImportedStowageService sOrderImportedStowageService;

    @Autowired
    private SOrderImportedFeedetailService sOrderImportedFeedetailService;


    @Override
    public SOrderImported getById(Long id) {
        if (null == id) {
            throw new BusinessException("未找到数据");
        }
        return sOrderImportedMapper.selectByPrimaryKey(id);
    }

    @Override
    public Map<String, Object> create(SOrderImportedVo order, Boolean isPublish) throws Exception {
        OrderByExcelVo orderByExcelVo = buildOrderExcelVo(order);
        return orderService.add(orderByExcelVo, isPublish);
    }

    @Override
    public List<Map<String, Object>> batchCreate(List<SOrderImportedVo> orders) throws Exception {
        logger.info("batch create order params: {}", JSON.toJSONString(orders));
        UserVo currentUserVo = userService.getCurrentUserVo();
        if (null == currentUserVo) {
            logger.error("import from excel not find current user");
            throw new BusinessException("未找到当前用户");
        }

        List<Map<String, Object>> resultList = new ArrayList<>();
        for (SOrderImportedVo order : orders) {
            OrderByExcelVo orderByExcelVo = buildOrderExcelVo(order);
            Map<String, Object> orderMap = orderService.add(orderByExcelVo, true);
            Map<String, Object> resultMap = new HashMap<String, Object>();
            if (null != orderMap) {
                resultMap.put("id", order.getId());
                resultMap.put("success", true);
                resultMap.put("orderCode", orderMap.get("ordercode"));
                Long orderId = Long.parseLong(orderMap.get("id").toString());
                orderService.publish(orderId, false);
                order.setStatus(OrderImporteStatusEnum.PUBLISHED.getValue());
                order.setStatusTxt(OrderImporteStatusEnum.PUBLISHED.getText());


                SOrderImported ordermodel = new SOrderImported();
                BeanUtils.copyProperties(ordermodel, order);
                sOrderImportedMapper.updateByPrimaryKeySelective(ordermodel);
            } else {
                resultMap.put("success", false);
            }
            resultList.add(resultMap);
        }

        return resultList;
    }

    @Override
    public SOrderImportedVo save(SOrderImportedVo orderImported) throws Exception {
        logger.info("save orderimport by id: {}", JSON.toJSONString(orderImported));
        if (null == orderImported || null == orderImported.getId()) {
            logger.error("SOrderImportedServiceImpl: save: id is empty.");
            throw new BusinessException("ID不能为空");
        }
        boolean isSuccess = buildOrderImport(orderImported);
        logger.info("SOrderImportedServiceImpl: save: after buildOrderImported:{} ", JSON.toJSONString(orderImported));
        if (orderImported.getSuccess()) {
            orderImported.setSuccess(true);
            orderImported.setMsg("");
            SOrderImported sOrderImported = new SOrderImported();
            BeanUtils.copyProperties(orderImported, sOrderImported);
            sOrderImported.setIsSuccess(true);
            sOrderImported.setErrorMessage("");
            sOrderImportedMapper.updateByPrimaryKeySelective(sOrderImported);
        } else {
            logger.error("SOrderImportedServiceImpl: save error: {} ", orderImported.getMsg());
            throw new BusinessException(orderImported.getMsg());
        }
        return orderImported;
    }

    @Override
    public List<SOrderImportedVo> importFromExcel(List<SOrderImportedVo> orders) throws Exception {
        logger.info("import from excel params: {} ", JSON.toJSONString(orders));
        UserVo currentUserVo = userService.getCurrentUserVo();
        //循环校验数据
        for (SOrderImportedVo orderImportedVo : orders) {
            Long userid = currentUserVo.getId();
            orderImportedVo.setUserId(userid);

            SOrderImported orderImported = new SOrderImported();

            BeanUtils.copyProperties(orderImportedVo, orderImported);
            sOrderImportedMapper.insertSelective(orderImported);
            orderImportedVo.setId(orderImported.getId());

            this.buildOrderImport(orderImportedVo); //校验并填充code值
            BeanUtils.copyProperties(orderImportedVo, orderImported);
            orderImported.setIsSuccess(orderImportedVo.getSuccess());
            orderImported.setErrorMessage(orderImportedVo.getMsg());
            sOrderImportedMapper.updateByPrimaryKeySelective(orderImported);

            // 添加id modify by [Tuffy] 何东阳
            orderImportedVo.setId(orderImported.getId());
        }
        return orders;
    }

    @Override
    public boolean del(List<Long> ids) {
        logger.info("delete order from import by ids: {}", ids);
        if (null != ids && ids.size() > 0) {
            int count = sOrderImportedExtMapper.delBatch(ids);
            logger.info("delete order from import by ids, count: {}", count);
            return count == ids.size();
        }
        return true;
    }

    /**
     * 构建 OrderImported
     *
     * @return
     */
    public boolean buildOrderImport(SOrderImportedVo orderImported) throws Exception {
        logger.info("import from excel validate order: {} ", JSON.toJSONString(orderImported));

        boolean isBuildOk = true;
        List<SOrderImportedVo.MsgObj> errObjects = new ArrayList<>();
        orderImported.setMsgObj(errObjects);
        orderImported.setMsg("");

        //车架号空和重复判断
        boolean isVinOK = true;
        String vinsStr = orderImported.getVins();
        if (StringUtils.isBlank(vinsStr)) {
            isVinOK = false;
        } else {
            //替换中英文逗号句号为英文逗号
            vinsStr = vinsStr.replaceAll("\\.|\\，|\\。|\\<|\\>", ",");

            List<String> list = Arrays.asList(vinsStr.split(","));

            //整理车架号
            String vin = list.stream().map(s -> s + ",").collect(StringBuffer::new, StringBuffer::append, StringBuffer::append).toString();
            orderImported.setVins(vin.substring(0, vin.length() - 1));

            List<String> errorList = list.stream().filter(o -> StringUtils.isBlank(o) == true || o.length() != 17).collect(Collectors.toList());
            //判断车架号是否重复
            List<String> vins = list.stream().distinct().collect(Collectors.toList());
            if (CollectionUtils.isEmpty(list) || CollectionUtils.isNotEmpty(errorList) || vins.size() != list.size()) {
                isVinOK = false;
            }
        }
        if (!isVinOK) {
            logger.error("buildOrderImport error vin is empty！");
            orderImported.setSuccess(false);
            orderImported.setMsg(orderImported.getMsg() + "车架号不能为空不可重复且长度为17位, ");
            this.addErrorFieldMsg(orderImported, errObjects, "vins", "车架号不能为空不可重复且且长度为17位");
        }


        orderImported.setSerialNumber(UniquenessFlagUnits.generateUniquenessFlag("SN"));


        logger.info("import from excel get branid by name: {}", orderImported.getBrandName());
        boolean isVehicleOK = true;
        List<BVehicle> vehicles = vehiclesService.selectLikeBrandNameANDVehicleName("%" + orderImported.getBrandName() + "%", "%" + orderImported.getVehicleName() + "%");
        BVehicle vehicle = null;
        if (null != vehicles && vehicles.size() > 0) {
            vehicle = vehicles.get(0);
            orderImported.setVehicleId(vehicle.getId());
            orderImported.setBrandId(vehicle.getBrandId());
        } else {
            orderImported.setSuccess(false);
            orderImported.setMsg(orderImported.getMsg() + "获取汽车车型错误, ");
            this.addErrorFieldMsg(orderImported, errObjects, "brandId", "获取汽车品牌错误");
            this.addErrorFieldMsg(orderImported, errObjects, "vehicleId", "获取汽车车型错误");
            isVehicleOK = false;
        }

        String vehicleClassStr = BVehicleConstant.DEFAULT_VEHICLE_CLASS;
        if (null != vehicle && StringUtils.isNotBlank(vehicle.getSysVehicleClass())) {
            vehicleClassStr = vehicle.getSysVehicleClass();
        }

        //构建用户地址
        boolean isAreaSuccess = this.buildUserAddress(orderImported, errObjects);
        //构建价格
        boolean isCostSuccess = false;
        if (isAreaSuccess) {
            isCostSuccess = this.buildCost(orderImported, vehicleClassStr);
        }

        orderImported.setStatus(OrderImporteStatusEnum.NOTPUBLISH.getValue()); //10:未发布，20:已发布
        orderImported.setStatusTxt(OrderImporteStatusEnum.NOTPUBLISH.getText());

        isBuildOk = isVinOK && isAreaSuccess && isVehicleOK && isCostSuccess;

        orderImported.setSuccess(isBuildOk);
        logger.info("import from excel build orderimported: {}", JSON.toJSONString(orderImported));
        return true;
    }

    /**
     * 导入发布
     *
     * @param soiv
     */
    public void publishByExcel(SOrderImportedVo soiv) throws Exception {
        Map<String, Object> map = orderService.addByExcel(soiv);
        Long id = (Long) map.get("id");
        orderService.publish(id, false);
        soiv.setStatus(OrderImporteStatusEnum.PUBLISHED.getValue());
        soiv.setStatusTxt(OrderImporteStatusEnum.PUBLISHED.getText());
        SOrderImported soi = new SOrderImported();
        BeanCopier beanCopierT = BeanCopier.create(SOrderImportedVo.class, SOrderImported.class, false);
        beanCopierT.copy(soiv, soi, null);
        sOrderImportedMapper.updateByPrimaryKeySelective(soi);
    }

    /**
     * 添加字段错误信息
     *
     * @param orderImported
     * @param errObjects
     * @param key
     * @param msg
     */
    private void addErrorFieldMsg(SOrderImportedVo orderImported, List<SOrderImportedVo.MsgObj> errObjects, String key, String msg) {
        SOrderImportedVo.MsgObj msgObj = orderImported.new MsgObj();
        msgObj.setKeystr(key);
        msgObj.setMsgstr(msg);
        errObjects.add(msgObj);
    }


    /**
     * 构建下单form
     *
     * @param order
     * @return
     */
    private OrderByExcelVo buildOrderExcelVo(SOrderImportedVo order) {
        logger.info("batch create order: {}", JSON.toJSONString(order));
        OrderByExcelVo orderorderByExcelVo = new OrderByExcelVo();

        BeanUtils.copyProperties(order, orderorderByExcelVo);
        orderorderByExcelVo.setProductId(order.getFeeProductId());

        logger.info("batch create order, build brans");
        String vinStr = order.getVins();
        String[] vins = vinStr.split(",");
        Map<String, Object> brands = new HashMap<>();
        brands.put("vehicleid", order.getVehicleId());
        brands.put("vehiclecount", vins.length);
        List<Map<String, Object>> vinList = new ArrayList<Map<String, Object>>();
        for (String vin : vins) {
            Map<String, Object> vinMap = new HashMap<String, Object>();
            vinMap.put("vin", vin);
            vinMap.put("color", "");
            vinList.add(vinMap);
        }
        brands.put("vins", JSON.toJSONString(vinList));
        List<Map<String, Object>> brandList = new ArrayList<Map<String, Object>>();
        brandList.add(brands);
        orderorderByExcelVo.setVehiclesbrands(JSON.toJSONString(brandList));
        return orderorderByExcelVo;
    }

    /**
     * 构建价格
     */
    @SuppressWarnings("unchecked")
    private boolean buildCost(SOrderImportedVo orderImported, String vehicleClassStr) throws Exception {
        String vinStr = orderImported.getVins();
        String[] vins = vinStr.split(",");
        orderImported.setAmount(vins.length);

        logger.info("import from excel get price bussFeesVo: departCountyCode:{}, receiptCountyCode:{}, vehicleClass:{}", orderImported.getDepartCountyCode(), orderImported.getReceiptCountyCode(), vehicleClassStr);

        //根据区县编码查询完整省市县
        String depaAddr = areaService.getFullByCode(orderImported.getDepartCountyCode());
        String destAddr = areaService.getFullByCode(orderImported.getReceiptCountyCode());

        //计算运距
        BigDecimal distance = mapService.distance(orderImported.getDepartCountyCode(), depaAddr,
                orderImported.getReceiptCountyCode(), destAddr);


        //查询车型分类信息
        BVehicleClass vehicleClass = bVehicleClassService.getByVehicleClass(vehicleClassStr);
        //组装车辆信息
        List<String> vin = Arrays.asList(orderImported.getVins().split(","));
        List<VehiClesInfoFrom> vehicles = new ArrayList<>();
        for (int i = 0; i < vin.size(); i++) {
            VehiClesInfoFrom from = new VehiClesInfoFrom();
            from.setAmount(1);
            from.setType(vehicleClass.getVehicleClass());
            from.setTypeId(vehicleClass.getId());
            vehicles.add(from);
        }

        //匹配配置模型
        List<Long> vehicleClassIds = Arrays.asList(vehicleClass.getId());
        List<Integer> vehicleNum = Arrays.asList(vin.size());
        BStowageModel stowageModel = bStowageVehicleService.computeSuitableStowage(BStowageModelEnum.ORDER, vehicleClassIds, vehicleNum);
        if (null != stowageModel) {
            //保存导入订单和配置模型关联
            sOrderImportedStowageService.add(orderImported.getId(), stowageModel.getId());
        }


        //查询费用
        Map<String, Object> map = feesService.queryFees(orderImported.getDepartCountyCode(),
                orderImported.getReceiptCountyCode(), distance, stowageModel, null, orderImported.getDeliveryDate(), Integer.valueOf(orderImported.getDeliveryTime()), vehicles, orderImported.getEstValue(), true,
                orderImported.getIsPick(), orderImported.getIsDeliv(), true, true);
        logger.info("import from excel get price bussFeesVo: {}", JSON.toJSONString(map));

        orderImported.setOrderCost((BigDecimal) map.get("total"));
        orderImported.setActualCost((BigDecimal) map.get("actualtotal"));
        orderImported.setDistance(distance);
        orderImported.setFeeProductId((long) map.get("productId"));
        orderImported.setArriveDate((Date) map.get("arrivalDate"));

        //保存导入订单费用详情
        ((List<SOrderFeeDetailVo>) map.get("fees")).stream().forEach(fee -> sOrderImportedFeedetailService.addFeeDetail(orderImported.getId(), fee.getId(), fee.getFeeName(), fee.getCost(), fee.getActualAmount()));

        return true;
    }


    /**
     * 构建用户地址
     *
     * @param orderImported
     * @return
     */
    private boolean buildUserAddress(SOrderImportedVo orderImported, List<SOrderImportedVo.MsgObj> errObjects) {
        boolean isSuccess = true;
        logger.info("import from excel get departcity area by city: {}, county:{} ", orderImported.getDepartCityName(), orderImported.getDepartCountyName());
        if (StringUtils.isBlank(orderImported.getDepartCountyName())) {
            orderImported.setDepartCountyName(App.COUNTY_NAME_DEFAULT);
        }
        //查询 提车地址
        List<BAreaSearchVo> departAreas = new ArrayList<>();
        if (StringUtils.isBlank(orderImported.getDepartCityName())) {
            orderImported.setSuccess(false);
            orderImported.setMsg(orderImported.getMsg() + "发车城市不能为空, ");
            addErrorFieldMsg(orderImported, errObjects, "departCity", "发车城市不能为空");
            isSuccess = false;
        } else {
            departAreas = areaService.selectLikename("", orderImported.getDepartCityName(), orderImported.getDepartCountyName());
            if (CollectionUtils.isEmpty(departAreas)) {
                orderImported.setSuccess(false);
                orderImported.setMsg(orderImported.getMsg() + "发车城市错误, ");
                addErrorFieldMsg(orderImported, errObjects, "departCity", "发车城市错误");
                isSuccess = false;
            } else if (departAreas.size() > 1) {
                String msg = "";
                for (BAreaSearchVo areaSearchVo : departAreas) {
                    msg += areaSearchVo.getCityName() + "-" + areaSearchVo.getCountyName() + " : ";
                }
                orderImported.setSuccess(false);
                orderImported.setMsg(orderImported.getMsg() + "匹配到多个发车城市:" + msg + ", ");
                addErrorFieldMsg(orderImported, errObjects, "departCity", "匹配到多个发车城市:" + msg);
                isSuccess = false;
            } else if (departAreas.size() == 1) {
                BAreaSearchVo departArea = departAreas.get(0);
                orderImported.setDepartProvinceCode(departArea.getProvinceCode());
                orderImported.setDepartProvinceName(departArea.getProvinceName());
                orderImported.setDepartCityCode(departArea.getCityCode());
                orderImported.setDepartCityName(departArea.getCityName());
                orderImported.setDepartCountyCode(departArea.getCountyCode());
                orderImported.setDepartCountyName(departArea.getCountyName());
            }
        }

        //查询交车地址
        logger.info("import from excel get receipt City area by city: {}, county:{}", orderImported.getReceiptCityName(), orderImported.getReceiptCountyName());
        if (StringUtils.isBlank(orderImported.getReceiptCountyName())) {
            orderImported.setReceiptCountyName(App.COUNTY_NAME_DEFAULT);
        }
        List<BAreaSearchVo> receiptAreas = new ArrayList<>();
        if (StringUtils.isBlank(orderImported.getReceiptCityName())) {
            orderImported.setSuccess(false);
            orderImported.setMsg(orderImported.getMsg() + "收车城市不能为空, ");
            addErrorFieldMsg(orderImported, errObjects, "receiptCity", "收车城市不能为空");
            isSuccess = false;
        } else {
            receiptAreas = areaService.selectLikename("", orderImported.getReceiptCityName(), orderImported.getReceiptCountyName());

            if (CollectionUtils.isEmpty(receiptAreas)) {
                orderImported.setSuccess(false);
                orderImported.setMsg(orderImported.getMsg() + "未匹配到收车城市, ");
                addErrorFieldMsg(orderImported, errObjects, "receiptCity", "未匹配到收车城市");
                isSuccess = false;
            } else if (receiptAreas.size() > 1) {
                String msg = "";
                for (BAreaSearchVo areaSearchVo : receiptAreas) {
                    msg += areaSearchVo.getCityName() + "-" + areaSearchVo.getCountyName() + " : ";
                }
                orderImported.setSuccess(false);
                orderImported.setMsg(orderImported.getMsg() + "匹配到多个收车城市:" + msg + ", ");
                addErrorFieldMsg(orderImported, errObjects, "departCity", "匹配到多个收车城市:" + msg);
                isSuccess = false;
            } else if (receiptAreas.size() == 1) {
                BAreaSearchVo receiptArea = receiptAreas.get(0);
                orderImported.setReceiptProvinceCode(receiptArea.getProvinceCode());
                orderImported.setReceiptProvinceName(receiptArea.getProvinceName());
                orderImported.setReceiptCityCode(receiptArea.getCityCode());
                orderImported.setReceiptCityName(receiptArea.getCityName());
                orderImported.setReceiptCountyCode(receiptArea.getCountyCode());
                orderImported.setReceiptCountyName(receiptArea.getCountyName());
            }
        }
        return isSuccess;
    }

    @Override
    public Map<String, Object> search(SOrderImportedSearchForm sOrderImportedSearchForm, PageVo page) throws Exception {
        SOrderImportedExample sOrderImportedExample = new SOrderImportedExample();
        sOrderImportedExample.setLimitStart(page.getStartIndex());
        sOrderImportedExample.setLimitEnd(page.getPageSize());

        SOrderImportedExample.Criteria criteria = sOrderImportedExample.createCriteria();

        UserVo currentUserVo = userService.getCurrentUserVo();
        if (null == currentUserVo) {
            logger.error("import from excel not find current user");
            throw new BusinessException("未找到当前用户");
        }
        criteria.andUserIdEqualTo(currentUserVo.getId());

        if (null != sOrderImportedSearchForm && StringUtils.isNotBlank(sOrderImportedSearchForm.getSnNumber())) {
            criteria.andSerialNumberEqualTo(sOrderImportedSearchForm.getSnNumber());
        }
        if (null != sOrderImportedSearchForm && StringUtils.isNotBlank(sOrderImportedSearchForm.getDepartProvinceCode())) {
            criteria.andDepartProvinceCodeEqualTo(sOrderImportedSearchForm.getDepartProvinceCode());
        }
        if (null != sOrderImportedSearchForm && StringUtils.isNotBlank(sOrderImportedSearchForm.getDepartCityCode())) {
            criteria.andDepartCityCodeEqualTo(sOrderImportedSearchForm.getDepartCityCode());
        }
        if (null != sOrderImportedSearchForm && StringUtils.isNotBlank(sOrderImportedSearchForm.getDepartCountryCode())) {
            criteria.andDepartCountyCodeEqualTo(sOrderImportedSearchForm.getDepartCountryCode());
        }
        if (null != sOrderImportedSearchForm && StringUtils.isNotBlank(sOrderImportedSearchForm.getReceiptProvinceCode())) {
            criteria.andReceiptProvinceCodeEqualTo(sOrderImportedSearchForm.getReceiptProvinceCode());
        }
        if (null != sOrderImportedSearchForm && StringUtils.isNotBlank(sOrderImportedSearchForm.getReceiptCityCode())) {
            criteria.andReceiptCityCodeEqualTo(sOrderImportedSearchForm.getReceiptCityCode());
        }
        if (null != sOrderImportedSearchForm && StringUtils.isNotBlank(sOrderImportedSearchForm.getReceiptCountryCode())) {
            criteria.andReceiptCountyCodeEqualTo(sOrderImportedSearchForm.getReceiptCountryCode());
        }
        if (null != sOrderImportedSearchForm && null != sOrderImportedSearchForm.getDepartDate()) {
            Calendar calendar1 = Calendar.getInstance();
            calendar1.setTime(sOrderImportedSearchForm.getDepartDate());
            calendar1.set(Calendar.HOUR_OF_DAY, 0);
            calendar1.set(Calendar.MINUTE, 0);
            calendar1.set(Calendar.SECOND, 0);

            Calendar calendar2 = Calendar.getInstance();
            calendar2.setTime(sOrderImportedSearchForm.getDepartDate());
            calendar2.set(Calendar.HOUR_OF_DAY, 23);
            calendar2.set(Calendar.MINUTE, 59);
            calendar2.set(Calendar.SECOND, 59);
            criteria.andDeliveryDateBetween(calendar1.getTime(), calendar2.getTime());
        }
        if (null != sOrderImportedSearchForm && null != sOrderImportedSearchForm.getReceiptDate()) {
            Calendar calendar1 = Calendar.getInstance();
            calendar1.setTime(sOrderImportedSearchForm.getReceiptDate());
            calendar1.set(Calendar.HOUR_OF_DAY, 0);
            calendar1.set(Calendar.MINUTE, 0);
            calendar1.set(Calendar.SECOND, 0);

            Calendar calendar2 = Calendar.getInstance();
            calendar2.setTime(sOrderImportedSearchForm.getReceiptDate());
            calendar2.set(Calendar.HOUR_OF_DAY, 23);
            calendar2.set(Calendar.MINUTE, 59);
            calendar2.set(Calendar.SECOND, 59);

            criteria.andArriveDateBetween(calendar1.getTime(), calendar2.getTime());
        }
        if (null != sOrderImportedSearchForm && null != sOrderImportedSearchForm.getImporteDate()) {
            Calendar calendar1 = Calendar.getInstance();
            calendar1.setTime(sOrderImportedSearchForm.getImporteDate());
            calendar1.set(Calendar.HOUR_OF_DAY, 0);
            calendar1.set(Calendar.MINUTE, 0);
            calendar1.set(Calendar.SECOND, 0);

            Calendar calendar2 = Calendar.getInstance();
            calendar2.setTime(sOrderImportedSearchForm.getImporteDate());
            calendar2.set(Calendar.HOUR_OF_DAY, 23);
            calendar2.set(Calendar.MINUTE, 39);
            calendar2.set(Calendar.SECOND, 59);

            criteria.andCreateTimeBetween(calendar1.getTime(), calendar2.getTime());
        }


        sOrderImportedExample.setOrderByClause(" update_time desc");
        page.setTotalRecord(sOrderImportedMapper.countByExample(sOrderImportedExample));
        List<SOrderImported> importedList = sOrderImportedMapper.selectByExample(sOrderImportedExample);

        //赋值到vo
        List<SOrderImportedVo> voList = new ArrayList<>();
        for (SOrderImported sorderImported : importedList) {
            SOrderImportedVo vo = new SOrderImportedVo();
            BeanUtils.copyProperties(sorderImported, vo);
            vo.setStatusTxt(OrderImporteStatusEnum.getByValue(sorderImported.getStatus()).getText());
            vo.setSuccess(sorderImported.getIsSuccess());
            vo.setMsg(sorderImported.getErrorMessage());
            voList.add(vo);
        }

        Map<String, Object> m = new HashMap<>();
        m.put("list", voList);
        m.put("page", page);

        return m;
    }
}
